import paramiko
import os

class ScpHelper:
    def __init__(self, local_folder,remote_host,username,password,remote_folder,port=22):
        self.local_folder = local_folder
        self.remote_host = remote_host
        self.username = username
        self.password = password
        self.remote_folder = remote_folder
        self.port = port
        self.SSHClient = None
        self.Transport = None
        self.SFTPClient = None

    def ssh_connect(self):
        self.SSHClient = paramiko.SSHClient()
        self.SSHClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 自动添加主机密钥
        self.SSHClient.connect(remote_host, port=22, username=username, password=password)

    # 创建sftp
    def sftp_connect(self):
        self.Transport = paramiko.Transport((remote_host, 22))
        self.Transport.connect(username=username, password=password)
        # 创建SFTP客户端
        self.SFTPClient = paramiko.SFTPClient.from_transport(self.Transport)


    # 文件夹传输
    def upload_folder(self,local_folder,remote_folder):
        self.sftp_connect()
        # 列出本地文件夹中的所有文件和文件夹
        for f in os.listdir(local_folder):
            local_file_path = os.path.join(local_folder, f)
            # remote_file_path = os.path.join(remote_folder, f)
            remote_file_path = f"{remote_folder}/{f}"
            print(os.path.isdir(local_file_path))
            if os.path.isdir(local_file_path):
                # 检查远程服务器是否已创建文件夹
                self.create_remote_folder(f)
                # 递归复制子文件夹
                self.upload_folder(local_file_path, remote_file_path)
            else:
                # 如果是文件，直接复制
                self.SFTPClient.put(local_file_path, remote_file_path)
                print("本地文件 ", f, "已上传到", self.remote_host, remote_file_path)
        self.Transport.close()
        self.SFTPClient.close()

	# 创建远程文件夹
    def create_remote_folder(self,path):
        self.ssh_connect()
        command = f"mkdir -p {self.remote_folder}/{path}"
        stdin, stdout, stderr = self.SSHClient.exec_command(command)
        print(command," 创建目录", self.remote_folder)
        self.SSHClient.close()

    def transform_data(self):
    	self.ssh_connect()
    	self.upload_folder(self.local_folder,self.remote_folder)
